package ee.battleship.game;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ee.battleship.classes.Game;
import ee.battleship.classes.Player;

/**
 * Servlet implementation class UserLogout
 */
@WebServlet("/UserLogout")
public class UserLogout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserLogout() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		@SuppressWarnings("unchecked")
//		HashMap<Integer, Game> games = (HashMap<Integer, Game>) getServletConfig().getServletContext().getAttribute("games");
		
		HttpSession session = request.getSession();
		
		Game game = (Game) session.getAttribute("game");
		Player player = (Player) session.getAttribute("player");
		DBConnection connection = new DBConnection();
		
		if (game != null) {			
			boolean success = game.getPlayers().remove(player);
			
			if (success) {
				game.setStatus(3);
				connection.updateGame(game);
			}
		}

		session.invalidate();
		response.sendRedirect("index.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
